package cyy.example.com.facotry.net.ConverterUtils;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.io.IOException;
import java.io.StringReader;

import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.net.RspCode;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by ChenYiYao on 2018/9/14.
 * des :
 */
public class CustomRspBodyCoverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    public CustomRspBodyCoverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        try {
            verify(json);
            return adapter.read(gson.newJsonReader(new StringReader(json)));
        } finally {

            value.close();
        }


    }

    private void verify(String json) {
        BaseEntity baseEntity = gson.fromJson(json, BaseEntity.class);
        if (RspCode.ERROR_ACCOUNT_TOKEN.equals(baseEntity.isSuccess())) {
            //token失效
            throw new MyException(baseEntity.msg);
        }
    }
}
